package com.ruoyi.demo.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.demo.domain.UserPhoto;
import com.ruoyi.demo.mapper.TakePhotoMapper;
import com.ruoyi.demo.service.ITakePhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

@Service
public class TakePhotoServiceImpl implements ITakePhotoService {
    
    @Autowired
    private TakePhotoMapper takePhotoMapper;

    @Override
    public String savePhoto(MultipartFile file, Long userId, String userName) throws Exception {
        // 构建文件名
        String timestamp = DateUtils.dateTimeNow();
        String fileName = userName + "_" + userId + "_" + timestamp + ".jpg";
        
        // 构建保存路径
        String filePath = RuoYiConfig.getProfile() + "/photos/";
        File dest = new File(filePath + fileName);
        
        // 确保目录存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        
        // 保存文件
        file.transferTo(dest);
        
        return "/photos/" + fileName;
    }

    @Override
    public int insertUserPhoto(UserPhoto userPhoto) {
        userPhoto.setCreatedAt(new Date());
        userPhoto.setIsDeleted("0");
        return takePhotoMapper.insertUserPhoto(userPhoto);
    }
}
